package com.lsh.radardemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.content.Intent;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.amap.api.maps.CameraUpdateFactory;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;
import java.io.IOException;

import android.os.Handler;
import android.util.Log;

import com.amap.api.maps.MapView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.MapsInitializer;


public class VehicleLocationActivity extends AppCompatActivity {
    private static final int REQUEST_LOCATION_PERMISSION = 100;
    private TextView tvLocation;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationCallback locationCallback;
    private Handler handler = new Handler();
    private Runnable timeoutRunnable;
    private static final int LOCATION_TIMEOUT_MS = 10000; // 10秒超时
    private Location lastLocation = null;
    private static final String GAODE_KEY = "2976b144b4407a9c22d5d037ec12c6ca"; // TODO: 替换为你自己的高德Web服务Key
    private OkHttpClient okHttpClient = new OkHttpClient();

    private MapView mapView;
    private AMap aMap;

    // 假设你已经有经纬度变量
    private double latitude = 39.90923;
    private double longitude = 116.3974267;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 必须在 super.onCreate 之前调用高德隐私合规代码
        MapsInitializer.updatePrivacyShow(this, true, true);
        MapsInitializer.updatePrivacyAgree(this, true);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vehicle_location);

        tvLocation = findViewById(R.id.tv_location);
        Button backButton = findViewById(R.id.btnBack);
        Button refreshButton = findViewById(R.id.btnRefresh);
        backButton.setOnClickListener(v -> finish());
        refreshButton.setOnClickListener(v -> refreshLocation());

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    return;
                }
                for (Location location : locationResult.getLocations()) {
                    lastLocation = location;
                    updateLocationInfo(location);
                    handler.removeCallbacks(timeoutRunnable); // 定位成功，移除超时
                    // 定位成功后立即停止更新
                    fusedLocationClient.removeLocationUpdates(locationCallback);
                    break; // 只处理一次
                }
            }
        };

        timeoutRunnable = () -> {
            tvLocation.setText("定位超时，请检查网络或定位服务，并可点击下方按钮重试。");
        };

        startLocationUpdatesWithTimeout();

        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState); // 必须写

        if (aMap == null) {
            aMap = mapView.getMap();
        }

        // 显示当前位置
        LatLng latLng = new LatLng(latitude, longitude);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
        aMap.addMarker(new MarkerOptions().position(latLng).title("车辆当前位置"));
    }

    private void refreshLocation() {
        tvLocation.setText("正在获取位置信息...");
        startLocationUpdatesWithTimeout();
    }

    private void startLocationUpdatesWithTimeout() {
        handler.removeCallbacks(timeoutRunnable);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION_PERMISSION);
        } else {
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setInterval(3000);
            locationRequest.setFastestInterval(2000);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
            handler.postDelayed(timeoutRunnable, LOCATION_TIMEOUT_MS);
        }
    }

    private void updateLocationInfo(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        StringBuilder sb = new StringBuilder();
        sb.append("经度: ").append(longitude).append("\n");
        sb.append("纬度: ").append(latitude).append("\n");
        runOnUiThread(() -> tvLocation.setText(sb.toString() + "详细地址: 正在获取..."));

        // 使用高德API逆地理编码
        String url = "https://restapi.amap.com/v3/geocode/regeo?location=" + longitude + "," + latitude + "&key=" + GAODE_KEY + "&radius=1000&extensions=base";
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> tvLocation.setText(sb.toString() + "详细地址: 获取失败"));
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String addressStr = "详细地址: 获取失败";
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Log.d("GAODE_API", body); // 打印返回内容
                    try {
                        JSONObject json = new JSONObject(body);
                        if ("1".equals(json.optString("status"))) {
                            JSONObject regeocode = json.optJSONObject("regeocode");
                            if (regeocode != null) {
                                addressStr = "详细地址: " + regeocode.optString("formatted_address", "未获取到");
                            }
                        }
                    } catch (Exception e) {
                        addressStr = "详细地址: 解析失败";
                    }
                }
                String finalAddressStr = addressStr;
                runOnUiThread(() -> tvLocation.setText(sb.toString() + finalAddressStr));
            }
        });

        // 显示车辆当前位置
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16));
        aMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("车辆位置"));
    }

    // 生命周期管理
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        fusedLocationClient.removeLocationUpdates(locationCallback);
        handler.removeCallbacks(timeoutRunnable);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocationUpdatesWithTimeout();
            } else {
                Toast.makeText(this, "需要定位权限才能获取位置信息", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
} 